package com.david.nfc

import android.app.Service
import android.content.Intent
import android.nfc.NfcAdapter
import android.nfc.Tag
import android.os.Build
import android.os.IBinder
import android.util.Log
import com.david.nfc.result.NfcParserUtil

class NfcService: Service() {

    override fun onCreate() {
        super.onCreate()
        NfcUtils.init(applicationContext)
        Log.e("nfc", "service oncreate...")

    }
    override fun onBind(intent: Intent?): IBinder? {
        return null
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        Log.e("nfc", "action is ${intent?.action}")
        intent?.let {
            val content = NfcUtils.readFromIntent(it)

            if (NfcAdapter.ACTION_TAG_DISCOVERED == it.action) {
                if (Build.VERSION.SDK_INT >= 33) {
                    NfcUtils.myTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG, Tag::class.java)
                } else {
                    NfcUtils.myTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG)
                }
            }
            parseResult(content)
        }

        return START_STICKY
    }

    private fun parseResult(content: String){
        NfcParserUtil.parseResult(application, content)
    }
}